package com.director.hibernate.json.impl.gson;

import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.hibernate.SessionFactory;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;

import java.lang.reflect.Type;

/**
 * @author Simone Ricciardi
 * @version 1.0, 04/07/2012
 */
public class ProxySerializer implements JsonSerializer {

   private final SessionFactory sessionFactory;

   public ProxySerializer(SessionFactory sessionFactory) {
      this.sessionFactory = sessionFactory;
   }

   @Override
   public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context) {

      if(src == null) {
         return context.serialize(src);
      }

      if(HibernateProxy.class.isInstance(src)) {
         LazyInitializer lazyInitializer = ((HibernateProxy) src).getHibernateLazyInitializer();
         if(lazyInitializer.isUninitialized()) {
            lazyInitializer.initialize();
         }
         src = lazyInitializer.getImplementation();
      }

      return context.serialize(src);
   }
}
